package com.jd.ssdb4j.base;

import com.jd.ssdb4j.SSDBs;
import com.jd.ssdb4j.exception.SSDBDataException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Response {

    public String status;
    public List<byte[]> raw;

    public Response(List<byte[]> raw){
        this.raw = raw;
        if(raw.size() > 0){
            status = new String(raw.get(0));
        }
    }

    public Object exception() throws Exception{
        if(raw.size() >= 2){
            throw new Exception(new String(raw.get(1)));
        }else{
            throw new Exception("");
        }
    }

    public boolean ok(){
        return status.equals("ok");
    }

    public boolean notFound(){
        return status.equals("not_found");
    }

	protected String _string(byte[] data) {
		return new String(data, SSDBs.DEFAULT_CHARSET);
	}

	public String asString() {

        if (raw.size() <= 1)
            throw new SSDBDataException(" raw size <= 1 ");

		return _string(raw.get(1));
	}

    public boolean asBoolean() {
        return Boolean.parseBoolean(asString());
    }

	public double asDouble() {
		return Double.parseDouble(asString());
	}

	public int asInt() {
		return Integer.parseInt(asString());
	}
	public long asLong() {
		return Long.parseLong(asString());
	}
	
	public List<String> listString() {

        List<String> list = new ArrayList<String>();

        for (int i=1; i<raw.size(); i++) {

            byte[] data = raw.get(i);
            list.add(_string(data));
        }

		return list;
	}
	
	public Map<String, Object> map() {

		if ((raw.size()-1) % 2 != 0)
			throw new SSDBDataException("not key-value pairs");

        Map<String, Object> map = new HashMap<String, Object>();

        for (int i=1; i<raw.size(); i+=2) {

            byte[] k = raw.get(i);
            byte[] v = raw.get(i+1);
            map.put(_string(k), v);
        }

		return map;
	}
	
	public Map<String, String> mapString() {

        if ((raw.size()-1) % 2 != 0)
            throw new SSDBDataException("not key-value pairs");

        Map<String, String> map = new HashMap<String, String>();

        for (int i=1; i<raw.size(); i+=2) {

            byte[] k = raw.get(i);
            byte[] v = raw.get(i+1);
            map.put(_string(k), _string(v));
        }

        return map;
	}

    public void setStatus(String status) {
        this.status = status;
    }

    public String getStatus() {
        return this.status;
    }

    public void setRaw(List<byte[]> raw) {
        this.raw = raw;
    }

    public List<byte[]> getRaw() {
        return this.raw;
    }
}
